// Copyright 2021 Guoyoko. All Rights Reserved.

#include "SWMainFrameModule.h"
#include "Modules/ModuleManager.h"
#include "Framework/Application/SlateApplication.h"
#include "Framework/Docking/TabManager.h"
#include "Widgets/SViewport.h"


void FSWMainFrameModule::StartupModule()
{
	if (!GIsEditor)
		FCoreDelegates::OnEndFrame.AddRaw(this, &FSWMainFrameModule::CreateMainFrame);

}

void FSWMainFrameModule::ShutdownModule()
{
}

void FSWMainFrameModule::CreateMainFrame()
{
	// Create custome game window /
	FVector2D GameWindowStartSize = FVector2D(1920, 1080);
	GameWindows = SNew(SWindow)
		.bDragAnywhere(true)
		.CreateTitleBar(false)
		.ClientSize(GameWindowStartSize)
		;

	FSlateApplication::Get().AddWindow(GameWindows.ToSharedRef(), true);

	// StartLayout,dont need loading from file
	TSharedRef<FTabManager::FLayout> Layout = FTabManager::NewLayout("StartLayout")
		->AddArea
		(
			FTabManager::NewPrimaryArea()
			->Split
			(
				FTabManager::NewStack()
				->AddTab("SWLevelEditor", ETabState::OpenedTab)
			)
		);

	// Create Editor View
	const bool bEmbedTitleAreaContent = true;
	TSharedPtr<SWidget> ContentWidget = FGlobalTabmanager::Get()->RestoreFrom(Layout, GameWindows.ToSharedRef(), bEmbedTitleAreaContent);
	GameWindows->SetContent(ContentWidget.ToSharedRef());

	// When close GameWindow, just close Engine's root window
	GameWindows->SetOnWindowClosed(FOnWindowClosed::CreateLambda([](const TSharedRef<SWindow>& InWindow)
		{
			InWindow->SetOnWindowClosed(FOnWindowClosed());
			InWindow->RequestDestroyWindow();

			FSlateApplication::Get().RequestDestroyWindow(GEngine->GameViewport->GetWindow().ToSharedRef());
		}));


	// Hide GameViewport Window /
	TSharedPtr<SWindow> DefaultRootWindow = GEngine->GameViewport->GetWindow();
	DefaultRootWindow->HideWindow();

	FCoreDelegates::OnEndFrame.RemoveAll(this);
}


//IMPLEMENT_PRIMARY_GAME_MODULE(FSWMainFrameModule, SplitWindowsMainFrame, "SplitWindows");
IMPLEMENT_MODULE(FSWMainFrameModule, SplitWindowsMainFrame);

